package com.songVersion.services.impl;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.songVersion.model.Search;
import com.songVersion.services.SearchManager;
import com.songVersion.utils.PMF;

public class SearchManagerImpl extends ManagerImpl<Search> implements SearchManager
{

	@SuppressWarnings("unchecked")
	public List<Search> getMaxSearched(int maxItems)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Search.class);
		query.setOrdering("hits desc");
		query.setRange(0, maxItems);
		List<Search> l = null;
		try
		{
			l = (List<Search>) query.execute();
			l.size();//avoid lazy loading!
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		pm.close();
		return l;
	}

	public Search save(String author, String song)
	{
		Search newSearch = loadSearch(author, song);
		if (newSearch == null)
		{
			newSearch = new Search(author, song, 0);
		}
		newSearch.addHit();
		newSearch = save(newSearch);
		return newSearch;
		
	}

	public Search loadSearch(String author, String song)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Search search = doLoadSearch(author, song, pm);
		if (search == null)
			search = new Search(author, song, 0);
		pm.close();
		return search;
	}

	/*
	private Search doSave(Search newSearch, PersistenceManager pm)
	{
		System.out.println("doSave!");
		pm.makePersistent(newSearch);
		return newSearch;
	}

*/
	@SuppressWarnings("unchecked")
	private Search doLoadSearch(String author, String song,
			PersistenceManager pm)
	{
		Query query = pm.newQuery(Search.class);
		query.setFilter("author == authorParam && song == songParam");
		query.declareParameters("String authorParam, String songParam");
		List<Search> l = (List<Search>) query.execute(author, song);
		if (l == null || l.size() == 0)
			return null;
		else
			return l.get(0);
	}

	@Override
	public void init()
	{
		this.t = new Search("", "");
		
	}
}
